//
//  GlobalVar.m
//  MyShoes
//
//  Created by mac on 11-7-4.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GlobalVar.h"
#import <sys/types.h>
#import <sys/sysctl.h>
#import <CommonCrypto/CommonDigest.h>
static GlobalVar* sharedInstance=nil;


@implementation GlobalVar
@synthesize isRecordTheErrorMsg;
+(GlobalVar*)sharedInstance
{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance=[[self alloc]init];
    });
    return sharedInstance;
    
}
+(NSString*)getVersion
{
    NSString *nsStrVer=SOFT_VER;
    float b = [nsStrVer floatValue]/10;
    return [NSString stringWithFormat:@"版本号 %0.1f",b];
}
+(NSString*)getTheBestIp
{
    NSString* best=[[NSUserDefaults standardUserDefaults] objectForKey:@"BEST"];
    // NSLog(@"best====%@",best);
    NSArray *nsArr = [best componentsSeparatedByString:@"http://"];
    nsArr = [(NSString*)nsArr[1] componentsSeparatedByString:@":"];
    //NSLog(@"narr =bb===%@",nsArr[0]);
    /*
     121.40.86.219:8002/appapi" forKey:@"121.40.86.219:8002"];
     119.147.137.16:8002/appapi" forKey:@"119.147.137.16:8002"];
     119.147.137.79:8002/appapi" forKey:@"119.147.137.79:8002"];
     61.145.116.124:8008/appapi" forKey:@"61.145.116.124:8008"];
     122.114.58.59:8002/appapi" forKey:@"122.114.58.59:8002"];
     121.41.25.193:8002/appapi" forKey:@"121.41.25.193:8002"];
     222.180.162.61:8008/appapi" forKey:@"222.180.162.61:8008"];
     113.207.26.202:8008/appapi" forKey:@"113.207.26.202:8008"];
     121.42.144.46:80/appapi" forKey:@"121.42.144.46:80"];
     */
    //119.147.137.16 122.114.58.59 nsArr[0];//
    return nsArr[0];
}
+(NSString*)md5Str:(NSString *)code
{
    NSString *str = [NSString stringWithFormat:@"%@",code];
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString
            stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1],
            result[2], result[3],
            result[4], result[5],
            result[6], result[7],
            result[8], result[9],
            result[10], result[11],
            result[12], result[13],
            result[14], result[15]
            ];
    

}


+(int)getTypeByPhoneNumber
{
    NSString *nsStrPhone = [GlobalVar loginUserKey];
    nsStrPhone = [nsStrPhone substringWithRange:NSMakeRange(0, 3)];
    NSArray *yd = [NSArray arrayWithObjects:@"134",@"135",@"136",@"137",@"138",@"139",@"147",@"150",@"151",@"152",@"157",@"158",@"159",@"182",@"183",@"184",@"187",@"188", nil];/*移动*/
    NSArray *dx = [NSArray arrayWithObjects:@"133",@"153",@"180",@"181" ,@"189",nil]; /*电信*/
    NSArray *lt = [NSArray arrayWithObjects:@"130",@"131",@"132",@"145",@"155",@"156",@"185",@"186", nil];/*联通*/
    //type 类型，比如：中国移动、中国电信、中国联通，分别是：0,1,2
    if ([yd indexOfObject:nsStrPhone] != NSNotFound)
    {
        return 0;
    }else if([dx indexOfObject:nsStrPhone] != NSNotFound)
    {
        return 1;
    }else if([lt indexOfObject:nsStrPhone] != NSNotFound)
    {
        return 2;
    }
    return -1;
}


+(NSString *)loginUserKey
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *key = [defaults objectForKey:@"LOGIN_USER_KEY"];
	return key;
}

+(NSString*)loginUserPass
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *theKey = [defaults objectForKey:@"LOGIN_USER_PASS"];
    return theKey;
}


+(NSString *)getFilePath:(NSString *)filename
{
	NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
	NSString *documentDirectory=[paths objectAtIndex:0];
	NSString *filePath=[documentDirectory stringByAppendingPathComponent:filename];
	return filePath;
}
+(NSArray*)getZhongzhuanUrls
{
   
    NSFileManager* fm=[NSFileManager defaultManager];
    if ([fm fileExistsAtPath:[GlobalVar getFilePath:@"zhongzhuanUrl.plist"]]) {
       NSArray* theArr=[NSArray arrayWithContentsOfFile:[GlobalVar getFilePath:@"zhongzhuanUrl.plist"]];
       
        if ([theArr count]>0) {
            return theArr;
        }
        
        
    }
    
    return nil;
    
}

+(NSString *) platformString
{
    
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5C (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5C (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5S (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5S (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    
    return platform;
    
    
    
}

+(NSString*)getPrefixUrl
{
   
    NSString* theAddress=[[NSUserDefaults standardUserDefaults] objectForKey:@"FINALLURL"];
    if ([theAddress length]>0) {
        return theAddress;
    }else if ([theAddress length]==0)
    {
        return  [NSString stringWithFormat:@"%@/%@",origin_url_prefix,@"proxy.php"];
    }
    
    return nil;

}


+(NSString*)getFinalExtaUrl
{
    NSString* theExtaUrl=[[NSUserDefaults standardUserDefaults] objectForKey:@"FINALKUOZHANURL"];
    if (theExtaUrl && [theExtaUrl length]>0) {
        return theExtaUrl;
    }else if ([theExtaUrl length]==0)
    {
        return EXTA_INTERFACE_URL;
    }
    
    
    
    return nil;
}


+(NSString*)getMultiAgentStr
{
    NSString* str=[[NSUserDefaults standardUserDefaults] objectForKey:@"multiAgent"];
    
    if ([str length]==0 || str==nil) {
        str=@"1";
    }
    return str;
}

+(NSString*)getTheCertNum
{
   
    NSString* certNum=@"";
    
    NSString* isOpenAgentAd=[[NSUserDefaults standardUserDefaults] objectForKey:@"agentAd"];
    if ([isOpenAgentAd isEqualToString:@"1"]) {
        certNum=[[NSUserDefaults standardUserDefaults] objectForKey:@"CERT_NUM"];
    }else
    {
        certNum=@"";
    }
    
    return certNum;

}


//判断状态栏网络状态
+(NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            
            switch (netType) {
                case 0:
                    state = @"无网络";
                    //无网模式
                    break;
                case 1:
                    state = @"2G";
                    break;
                case 2:
                    state = @"3G";
                    break;
                case 3:
                    state = @"4G";
                    break;
                case 5:
                {
                    state = @"WIFI";
                }
                    break;
                default:
                    break;
            }
        }
    }
    
    //根据状态选择
    return state;
    
}

-(void)saveUserMsg
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    NSDate* theDate=[NSDate date];
    NSDateFormatter* formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString* theLastTime=[formatter stringFromDate:theDate];
    
    NSLog(@"theLastTime:%@",theLastTime);

  
    [IPDetector getWANIPAddressWithCompletion:^(NSString *IPAddress) {
        
        NSUserDefaults* defaults1=[NSUserDefaults standardUserDefaults];
        
        NSLog(@"外网ip地址:%@",IPAddress);
       
        [defaults1 setObject:IPAddress forKey:@"remoteIP"];
        [defaults synchronize];
       

        
    }];
    
    [defaults setObject:[GlobalVar getNetWorkStates] forKey:@"apn"];
    [defaults setObject:theLastTime forKey:@"theDate"];
    [defaults setBool:YES forKey:@"isRecMsg"];
    [defaults synchronize];
    
    

}





+(void)createEditableDataBaseIfNeeded
{
    
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    
    NSString* writableDBPath=[GlobalVar getFilePath:@"result.txt"];
   // NSLog(@"the writable db path:%@",writableDBPath);
    
    BOOL dbExits=[fileManager fileExistsAtPath:writableDBPath];
    
    if (!dbExits) {
        
        NSString* defaultPath=[[NSBundle mainBundle] pathForResource:@"result" ofType:@"txt"];
        NSError* error;
        BOOL success=[fileManager copyItemAtPath:defaultPath toPath:writableDBPath error:&error];
        
        if (!success) {
            NSAssert1(0, @"错误写入文件:'%@'.", [error localizedDescription]);
            
        }
    }
    

    
}

+(void)alert:(NSString *)msg
{
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    [alertView release];
}

+(NSString*)getTheBestUrl
{
    NSString* best=[[NSUserDefaults standardUserDefaults] objectForKey:@"BEST"];
    return best;
}


+(void)writeTheInfoToTheLocal:(NSString*)infro

{
    [GlobalVar createEditableDataBaseIfNeeded];
    
    infro = [NSString stringWithFormat:@"%@%@",@"IOS|", infro];
    
    NSString* isUpdateFile=[[NSUserDefaults standardUserDefaults] objectForKey:@"UPDATEFILE"];
    
    if ([isUpdateFile intValue]==1)
    {
        NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:[GlobalVar getFilePath:@"result.txt"]];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:[infro dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandler closeFile];
    }
}



+(UInt64)preRequestTime:(UInt64)preTimeChuo AndAfterRequestTime:(UInt64)afterTimeChuo
{
    UInt64 theResult=afterTimeChuo-preTimeChuo;
    return theResult;
}

+(UInt64)getTimeChuo
{
    
    UInt64 recordTime=[[NSDate date] timeIntervalSince1970]*1000;
    // NSLog(@"请求后%llu",recordTime);
    return recordTime;
}

+(NSString*)getBundleIdentifierAndCurrentDate
{
    NSString* bundleIdientifyAndCurrentDate=nil;
    
    
    
    NSString* bundleIdentifier=[[NSBundle mainBundle] bundleIdentifier];
    
    NSDateFormatter* formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* currentDate =[formatter stringFromDate:[NSDate date]];
    
    bundleIdientifyAndCurrentDate=[NSString stringWithFormat:@"%@  %@",currentDate,bundleIdentifier];
    return bundleIdientifyAndCurrentDate;
}

+(int)getCarrierNetWorkSignal
{
    void *libHandle = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_LAZY);
    int (*CTGetSignalStrength)();
    CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength");
   if( CTGetSignalStrength == NULL) NSLog(@"Could not find CTGetSignalStrength");
    int result = CTGetSignalStrength();
    NSLog(@"网络信号强度:%d",result);
  //  dlclose(libHandle);
    return result;
}
@end
